import { Controller, Context, Post, Use, sfn, Get } from "nb2";
import { ResBody, Token } from "../common/model.js";
import { prisma } from "../prisma.js";
import { handleAuth } from "../common/handleAuth.js";
import { getToken } from "../common/utils.js";

@Controller("relation")
export class Relation {
  //查询关注关系
  @Get("follow/:to_uid")
  async [sfn()](ctx: Context) {
    const token = await getToken(ctx);
    const to_uid = Number(ctx.params.to_uid);
    let followed = false;
    if (token) {
      const follow = await prisma.follow.findFirst({
        where: {
          userId: token.uid,
          toUserId: to_uid,
        },
      });
      followed = !!follow;
    }
    ctx.json<ResBody>({ code: 200, followed });
  }

  @Use(handleAuth)
  @Post("switch-follow/:to_uid")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const to_uid = Number(ctx.params.to_uid);
    if (token.uid === to_uid) {
      ctx.json<ResBody>({ code: 400, msg: "你不能关注自己" });
    }

    let follow = await prisma.follow.findFirst({
      where: {
        userId: token.uid,
        toUserId: to_uid,
      },
    });

    let follow_id = null;

    if (follow) {
      await prisma.follow.delete({ where: { id: follow.id } });
    } else {
      follow = await prisma.follow.create({
        data: { userId: token.uid, toUserId: to_uid },
      });
      follow_id = follow.id;
    }
    ctx.json<ResBody>({
      code: 200,
      followed: !!follow_id,
      msg: follow_id ? "关注成功" : "取消关注",
    });
  }

  @Use(handleAuth)
  @Post("switch-collect/:gid")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const gid = Number(ctx.params.gid);

    let like = await prisma.collect.findFirst({
      where: {
        userId: token.uid,
        goodsId: gid,
      },
    });

    let collect_id = null;

    if (like) {
      await prisma.collect.delete({ where: { id: like.id } });
    } else {
      like = await prisma.collect.create({
        data: {
          userId: token.uid,
          goodsId: gid,
        },
      });
      collect_id = like.id;
    }

    ctx.json<ResBody>({
      code: 200,
      msg: collect_id ? "收藏成功" : "取消收藏",
      collect_id,
    });
  }

  @Use(handleAuth)
  @Post("switch-like/:gid")
  async [sfn()](ctx: Context) {
    const token = ctx.custom.token as Token;
    const gid = Number(ctx.params.gid);

    let like = await prisma.like.findFirst({
      where: {
        userId: token.uid,
        goodsId: gid,
      },
    });

    let like_id = null;

    if (like) {
      await prisma.like.delete({ where: { id: like.id } });
    } else {
      like = await prisma.like.create({
        data: {
          userId: token.uid,
          goodsId: gid,
        },
      });
      like_id = like.id;
    }

    ctx.json<ResBody>({
      code: 200,
      msg: like_id ? "点赞成功" : "取消点赞",
      like_id,
    });
  }
}
